import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:rabbit_mobile/i18n/strings.g.dart';
import '../view//Home//index.dart';
import '../view/Category/index.dart';
import '../view/ShoppingCart/index.dart';
import '../view/Mine/index.dart';
import '../widget/FramesAnimation/index.dart';

class Routers extends StatefulWidget {
  final int? initialIndex;

  const Routers({super.key, this.initialIndex = 0});

  @override
  State<Routers> createState() => _RoutersState();
}

class _RoutersState extends State<Routers> {
  /// 当前首页路由索引
  int _currentIndex = 0;
  late PageController? _pageController;

  /// 首页视口数组
  // ignore: non_constant_identifier_names
  List<Widget> BottomTab = const [
    Home(),
    Category(),
    ShoppingCart(),
    Mine(),
  ];

  /// 存放帧动画组件的key
  List<GlobalKey<FramesAnimationsState>> framesKeys = [
    GlobalKey<FramesAnimationsState>(debugLabel: 'home_key'),
    GlobalKey<FramesAnimationsState>(debugLabel: 'cate_key'),
    GlobalKey<FramesAnimationsState>(debugLabel: 'shop_key'),
    GlobalKey<FramesAnimationsState>(debugLabel: 'mine_key'),
  ];

  /// 上一次被选中的索引
  int _lastIndex = 0;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex!;
    _lastIndex = _currentIndex;
    _pageController = PageController(initialPage: _currentIndex);
    // 默认触发首页动画
    WidgetsBinding.instance.addPostFrameCallback((_) {
      framesKeys[_currentIndex].currentState?.startAnimation();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _pageController!.dispose();
  }

  /// 加载首页帧动画图片
  List<Image> _loadHomeFrames() {
    List<Image> images = [];
    for (var i = 0; i < 24; i++) {
      images.add(Image.asset(
        'assets/home_frames/home_frame_$i.png',
        width: 20.0,
        height: 20.0,
        gaplessPlayback: true, // 图片切换避免白屏
      ));
    }
    return images;
  }

  /// 加载分类帧动画图片
  List<Image> _loadCateFrames() {
    List<Image> images = [];
    for (var i = 0; i < 24; i++) {
      images.add(Image.asset(
        'assets/category_frames/category_frame_$i.png',
        width: 20.0,
        height: 20.0,
        gaplessPlayback: true, // 图片切换避免白屏
      ));
    }
    return images;
  }

  /// 加载购物车帧动画图片
  List<Image> _loadCartFrames() {
    List<Image> images = [];
    for (var i = 0; i < 24; i++) {
      images.add(Image.asset(
        'assets/cart_frames/cart_frame_$i.png',
        width: 20.0,
        height: 20.0,
        gaplessPlayback: true, // 图片切换避免白屏
      ));
    }
    return images;
  }

  /// 加载我的帧动画图片
  List<Image> _loadMineFrames() {
    List<Image> images = [];
    for (var i = 0; i < 24; i++) {
      images.add(Image.asset(
        'assets/mine_frames/mine_frame_$i.png',
        width: 20.0,
        height: 20.0,
        gaplessPlayback: true, // 图片切换避免白屏
      ));
    }
    return images;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        physics: const NeverScrollableScrollPhysics(),
        controller: _pageController,
        children: BottomTab,
      ),
      bottomNavigationBar: Theme(
        data: ThemeData(
            splashColor: Colors.transparent, // 消除点击时背景色
            highlightColor: Colors.transparent // 消除长按时的背景色
            ),
        child: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          currentIndex: _currentIndex,
          selectedFontSize: 10.0,
          unselectedFontSize: 10.0,
          selectedItemColor: Colors.teal,
          unselectedItemColor: Colors.grey,
          backgroundColor: Colors.white,
          onTap: (int value) {
            // 防止重复点击同一个标签
            if (_lastIndex == value) return;
            // 延迟触发帧动画，确保组件已挂载
            WidgetsBinding.instance.addPostFrameCallback(
              (_) {
                // 1. 先启动新标签的动画
                if (framesKeys[value].currentState != null) {
                  framesKeys[value].currentState?.startAnimation();
                } else {}
                // 2. 重置上一个标签的动画，前提是两个标签不相同
                if (_lastIndex != value && framesKeys[_lastIndex].currentState != null) {
                  framesKeys[_lastIndex].currentState?.resetAnimation();
                } else if (framesKeys[_lastIndex].currentState == null) {}
              },
            );

            // 更新 Beamer 路由
            String path = '/';
            switch (value) {
              case 0:
                path = '/';
                break;
              case 1:
                path = '/category';
                break;
              case 2:
                path = '/shopping_cart';
                break;
              case 3:
                path = '/mine';
                break;
            }

            Beamer.of(context).beamToNamed(path);

            // 更新上一次的索引
            _lastIndex = value;

            // 切换页面
            _pageController!.jumpToPage(value);

            setState(() {
              _currentIndex = value;
            });
          },
          items: [
            BottomNavigationBarItem(
              activeIcon: FramesAnimations(
                key: framesKeys[0],
                initIndex: 0,
                images: _loadHomeFrames(),
              ),
              icon: Image.asset('assets/home_nor.png', width: 20, height: 20),
              label: t.homepage,
            ),
            BottomNavigationBarItem(
              activeIcon: FramesAnimations(
                key: framesKeys[1],
                initIndex: 1,
                images: _loadCateFrames(),
              ),
              icon: Image.asset('assets/category_nor.png', width: 20, height: 20),
              label: t.categories,
            ),
            BottomNavigationBarItem(
              activeIcon: FramesAnimations(
                key: framesKeys[2],
                initIndex: 2,
                images: _loadCartFrames(),
              ),
              icon: Image.asset('assets/cart_nor.png', width: 20, height: 20),
              label: t.shoppingcart,
            ),
            BottomNavigationBarItem(
              activeIcon: FramesAnimations(
                key: framesKeys[3],
                initIndex: 3,
                images: _loadMineFrames(),
              ),
              icon: Image.asset('assets/mine_nor.png', width: 20, height: 20),
              label: t.my,
            ),
          ],
        ),
      ),
    );
  }
}
